package com.pfzy.lib.net.convert;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.pfzy.lib.net.BaseEntity;
import com.pfzy.lib.net.utils.ParamsUtils;

import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import okhttp3.ResponseBody;
import okio.BufferedSource;
import retrofit2.Converter;

public class FastJsonResponseConverter<T> implements Converter<ResponseBody, T> {
    private final Type type;

    public FastJsonResponseConverter(Type type) {
        this.type = type;
    }

    @Override
    public T convert(ResponseBody value) throws IOException {
        BufferedSource bufferedSource = value.source();
        String r2 = bufferedSource.readUtf8();
        bufferedSource.close();
        try {
            return JSONObject.parseObject(r2, this.type, new Feature[0]);
        } catch (Exception e) {
            if (ParamsUtils.getRawType(this.type) == String.class) {
                return (T) r2;
            }
            if (ParamsUtils.getRawType(this.type) == BaseEntity.class) {
                return repairBaseEntity(r2);
            }
            return null;
        }
    }

    private T repairBaseEntity(String response) {
        BaseEntity r1 = new BaseEntity();
        JSONObject jsonObject = JSONObject.parseObject(response);
        r1.code = jsonObject.getIntValue("code");
        r1.message = jsonObject.getString("message");
        r1.data = null;
        Type[] args = ((ParameterizedType) this.type).getActualTypeArguments();
        if ((args != null || args.length != 0) && ParamsUtils.getRawType(args[0]) == String.class) {
            JSONObject object = JSONObject.parseObject(response);
            r1.data = (T) object.get("data").toString();
        }
        return (T) r1;
    }
}
